from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
import datetime
import django.dispatch
from django.contrib import admin
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from pirate_signals.models import notification_send


class Message(models.Model):
    sender = models.ForeignKey(User, null=True, related_name="message_sender")
    receiver = models.ForeignKey(User, related_name="message_receiver")
    text = models.TextField(max_length=1200)
    created_dt = models.DateTimeField()
    read = models.BooleanField()
    
class Notification(models.Model):
    receiver = models.ForeignKey(User, related_name="notification_receiver")
    sender = models.ForeignKey(User, related_name="notification_sender")
    text = models.TextField(max_length=1200)
    link = models.CharField(max_length=250)
    content_type = models.ForeignKey(ContentType,
                                      verbose_name=_('content type'),
                                      related_name="content_type_set_for_%(class)s")
    object_pk = models.IntegerField(_('object ID'))
    content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
    is_read = models.BooleanField()
    submit_date = models.DateTimeField("date_sent")
        
    def __unicode__(self):
        return str(self.content_type) + ':' + str(self.object_pk)
    
admin.site.register(Notification)
    
#obj specifies the obj being replied to, new_obj specifies the new object
def create_notification(obj,reply_to,**kwargs):
    if obj.user != reply_to.user:
        content_type = ContentType.objects.get_for_model(obj)
        rep_type = ContentType.objects.get_for_model(reply_to)
        if len(obj.text) > 30: tt = str(obj.text)[0:30] + "..."
        else: tt = str(obj.text)
        text = str(obj.user.username) + " replied to your " + str(rep_type) + ": " + tt
        link = obj.get_absolute_url()
        notif = Notification(receiver=reply_to.user, sender=obj.user,text=text,link=link,content_type=rep_type,object_pk=reply_to.pk,is_read=False,submit_date=datetime.datetime.now())
        notif.save()
    
notification_send.connect(create_notification)    


